import { TRADE_STRATEGY, PROGARM_STATUS, SUBMIT_TYPE } from '../constant/enums';
import {
  SAVE_BUTTON_CODE,
  EXPORT_BUTTON_CODE,
  SUBMIT_BUTTON_CODE,
  TIMELY_BUTTON_CODE,
} from '../constant';
import { arrHasElement } from './element';
// 获取默认展示方案的id
export const findDefaultProgramId = (programList, username) => {
  if (!arrHasElement(programList)) {
    return null;
  }
  for (let i = 0; i < programList.length; i++) {
    let item = programList[i];
    let reg = new RegExp(`^${username}\\d+$`);
    if (reg.test(item.title)) {
      return item.id;
    }
  }
  return programList[0].id;
};

// 方案修改行的交易策略后，获取payload
export const getChangeTradeStrategyPayload = (originHourOrderInfos, tradeStrategyType) => {
  let modifyInfo = {};
  originHourOrderInfos.forEach((item) => (modifyInfo[item.hourOrder] = { tradeStrategyType }));
  return modifyInfo;
};

// 获取新方案的方案名
export const getNewProgramName = (username, programList) => {
  if (!arrHasElement(programList)) {
    return `${username}1`;
  }
  let userProgramList = programList.filter((item) =>
    new RegExp(`^${username}\\d+$`).test(item.title),
  );
  if (!arrHasElement(userProgramList)) {
    return `${username}1`;
  }

  return `${username}${
    Math.max.apply(
      null,
      userProgramList.map((item) =>
        parseInt(item.title.match(new RegExp(`^${username}(\\d+)$`))[1]),
      ),
    ) + 1
  }`;
};

// 获取新建方案时的默认方案
export const getNewProgramInfo = (title) => ({
  programInfo: {
    id: '-1',
    title,
    status: PROGARM_STATUS.CREATE,
    timelySubmitTime: null,
    adjust: true,
    remove: true,
  },
  hourOrderList: Array.from({ length: 24 }, (_, index) => index + 1).map((hourOrder) => ({
    hourOrder,
    tradeStrategyType: TRADE_STRATEGY.NO_STRATEGY,
    submitType: SUBMIT_TYPE.INSTALLED_CAPACITY,
    buyPowerLimit: 0.0,
    sellPowerLimit: 0.0,
    power: 0,
    price: 0,
  })),
});

// 获取页面的按钮权限
export const getButtonPermission = (permissions) => {
  let save = false,
    submit = false,
    timely = false,
    exportP = false;
  for (let index = 0; index < permissions.length; index++) {
    const { menuCode } = permissions[index];
    if (save && submit && timely && exportP) break;
    switch (menuCode) {
      case SAVE_BUTTON_CODE:
        save = true;
      case SUBMIT_BUTTON_CODE:
        submit = true;
      case TIMELY_BUTTON_CODE:
        timely = true;
      case EXPORT_BUTTON_CODE:
        exportP = true;
    }
  }
  return { save, submit, timely, export: exportP };
};
